package com.liuduidui.sh.utils;

import com.liuduidui.sh.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: es7-mo
 * @description: 实体类封装的工具类
 * @author: WEN
 * @create: 2020-07-25 
 **/
public class UtilOfKeyWord {
 
 
    public static void main(String[] args) throws Exception{
        // parseJD("java").forEach(System.out::println);
        parseJD("开发").forEach(content -> System.out.println(content));
    }
    public static List<Content> parseJD(String keyword) throws Exception {
 
        String url = "https://search.jd.com/Search?keyword="+keyword;
        Document document = Jsoup.parse(new URL(url), 30000);
        org.jsoup.nodes.Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");
        ArrayList<Content> list = new ArrayList<>();
        for ( Element el : elements){
            String img=  el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            list.add(content);
        }
        return  list;
    }
 
 
}